# This example shows how ApMon can be used as a simple host sensor to monitor and send
# the desired parameters to the MonALISA service (configured in the given file/url)
use strict;
use warnings;

use Net::Domain;
use File::Spec;
use ApMon;

# redirect output
#open STDOUT,">/dev/null";
#open STDERR,">/dev/null";

my $apm = new ApMon("http://aaf.cern.ch/config/monalisa_CAF.conf");

my $my_host = Net::Domain::hostfqdn();
#print "$my_host\n";
my $cluster="PROOF::CAF::STORAGE_xrootd_Nodes";

# the background data about the system will be sent with this cluster and node
$apm->setMonitorClusterNode($cluster, $my_host);

# sleep forever
while(1){
  my $count = 0;
  open(DATE, "ps ax -o user,command | grep proofslave | grep -v grep | cut -f1 -d' ' | sort | uniq | wc -l |");
  $count = <DATE>;
  close(DATE);
  
  my $xproofdup = 0;
  open(DATE, "ps aux | grep xproofd | grep -v grep | wc -l|");
  $xproofdup = <DATE>;
  close(DATE);

  my $xrootdup = 0;
  open(DATE, "ps aux | grep xrootd | grep -v grep | wc -l|");
  $xrootdup = <DATE>;
  close(DATE);

  my $olbdup = 0;
  open(DATE, "ps aux | grep cmsd | grep -v grep | wc -l|");
  $olbdup = <DATE>;
  close(DATE);

#print " count: $count\n xproofd: $xproofdup xrootd: $xrootdup olbd: $olbdup";
#my $xrootd_dir;
#(undef, undef, $xrootd_dir) = File::Spec->splitpath($ENV{AAF_MONALISA_XROOTD_DIR});
#my $xrootd_ver = (split('_', $xrootd_dir))[1];

my $xrootd_ver = File::Spec->splitpath($ENV{AAF_MONALISA_XROOTD_DIR});
my $proof_ver = File::Spec->splitpath($ENV{AAF_MONALISA_PROOF_DIR});

#print "$xrootd_ver\n";
#print "$proof_ver\n";

  $apm->sendParameters($cluster, $my_host, { "proofserv_count" => $count, "xproofd_up" => $xproofdup, "xrootd_up" => $xrootdup, "cmsd_up" => $olbdup}, "xrootd_ver" => $xrootd_ver, "proof_ver" => $proof_ver);
  sleep 10;
}
